package com.common.annotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author liuxuhuang
 * @date 2023年03月31日 22:41
 */
public class EnumValidtor implements ConstraintValidator<EnumValid, Object> {
    String validField;
    Class<?>[] classes;

    @Override
    public void initialize(EnumValid constraintAnnotation) {
        classes = constraintAnnotation.target();
        validField = constraintAnnotation.validField();
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext context) {
        if (o != null && o.toString().length() > 0 && classes.length > 0) {
            for (Class<?> c : classes) {
                try {
                    if (c.isEnum()) {
                        Object[] objects = c.getEnumConstants();
                        Method method = c.getMethod("name");
                        for (Object object : objects) {
                            Object invoke = method.invoke(object, null);
                            if (o.equals(invoke.toString())) {
                                return true;
                            }
                        }
                        Method cMethod = c.getMethod(validField);
                        for (Object object : objects) {
                            Object invoke = cMethod.invoke(object, null);
                            if (o.toString().equals(invoke.toString())) {
                                return true;
                            }
                        }
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        } else {
            return true;
        }
        return false;
    }
}
